package com.lwj.liwanjia.view.activity.address;


import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.DbAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.AddAdressBean;
import com.lwj.liwanjia.bean.AddressBean;
import com.lwj.liwanjia.bean.DbBean;
import com.lwj.liwanjia.bean.EditAddressBean;
import com.lwj.liwanjia.impl.AddAddressView;
import com.lwj.liwanjia.impl.EditAddressView;
import com.lwj.liwanjia.presenter.AddAddressPresenter;
import com.lwj.liwanjia.presenter.EditAddressPresenter;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.view.activity.login.LoginActivity;
import com.lwj.liwanjia.view.activity.login.RegisterActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 修改地址
 */
public class BianjiAddressActivity extends BaseActivity implements AddAddressView, EditAddressView {

    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.ed_shouhuoren)
    EditText edShouhuoren;
    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.tv_privoce)
    TextView tvPrivoce;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_district)
    TextView tvDistrict;
    @BindView(R.id.ed_jiedao)
    TextView edJiedao;
    @BindView(R.id.ed_detail_address)
    EditText edDetailAddress;
    @BindView(R.id.rl_moren)
    RelativeLayout rlMoren;//设为默认
    @BindView(R.id.iv_select)
    ImageView ivMoren;//设为默认

    private File dbFile;//存储省市区数据的文件
    private DbAdapter mAdapter;
    private PopupWindow popupWindow;//展示省市区的控件
    private List<DbBean> provinceList = new ArrayList();//省的数据集合
    private List<DbBean> cityList = new ArrayList<>();//市的数据集合
    private List<DbBean> districtList = new ArrayList();//区的数据集合
    private ListView cityListView;//市的数据集合
    private ListView districtListView;//区的数据集全
    private ListView provinceListView;//省的数据集合
    private SpfUtils spfUtils;
    private String loaction;
    private String token;
    private AddAddressPresenter addressPresenter;
    private EditAddressPresenter editAddressPresenter;
    private Map<String, Object> map = new HashMap<>();
    private double latitude;
    private double longitude;
    private int isFirst = 0;
    private String consigneeId;//地址ID

    @Override
    protected void initView() {
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText("编辑地址");
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("保存");
        consigneeId = getIntent().getStringExtra("consigneeId");
        spfUtils = SpfUtils.getSpfUtils(this);
        addressPresenter = new AddAddressPresenter(this);
        editAddressPresenter = new EditAddressPresenter(this);
        token = spfUtils.getToken();
        //读取数据库到文件中
        initDbToFile();
        //初始化PopupWindow
        initPopuoWindow();
        //省份的条目点击事件
        initProvinceListener();
        //市的条目点击事件
        initCityListener();
        //区的条目点击事件
        initDistrictListener();
    }

    @Override
    protected void initData() {
        if (consigneeId != null) {
            editAddressPresenter.editAddress(token, consigneeId);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bianji_address;
    }


    @OnClick({R.id.tv_left, R.id.tv_right, R.id.tv_privoce, R.id.tv_city, R.id.tv_district, R.id.ed_jiedao, R.id.rl_moren})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left://返回
                finish();
                break;
            case R.id.tv_right://保存
                getMaps();
                break;
            case R.id.tv_privoce://省
                //初始化省份数据并设置适配器
                initProvince();
                provinceListView.setVisibility(View.VISIBLE);
                cityListView.setVisibility(View.GONE);
                districtListView.setVisibility(View.GONE);
                //显示popupWindow
                popupWindow.showAsDropDown(tvPrivoce);
                break;
            case R.id.tv_city://市
                //先点击省,才能点击市
                if (cityList.size() > 0) {
                    provinceListView.setVisibility(View.GONE);
                    cityListView.setVisibility(View.VISIBLE);
                    districtListView.setVisibility(View.GONE);
                    popupWindow.showAsDropDown(tvCity);
                } else {
                    Toast.makeText(this, "请先选择省份", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_district://区
                //情况一:先选择市,才能选择区
                if (districtList.size() > 0) {
                    provinceListView.setVisibility(View.GONE);
                    cityListView.setVisibility(View.GONE);
                    districtListView.setVisibility(View.VISIBLE);
                    popupWindow.showAsDropDown(tvDistrict);
                } else {
                    Toast.makeText(this, "请先选择市", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.ed_jiedao://街道
                Intent intent = new Intent(BianjiAddressActivity.this, AmapActivity.class);
                startActivityForResult(intent, 4);
                break;
            case R.id.rl_moren://设为默认地址
                if (isFirst == 0) {//未设置成默认地址
                    ivMoren.setImageResource(R.mipmap.kuang_1);
                    isFirst = 1;
                } else if (isFirst == 1) {//设置成了默认地址
                    ivMoren.setImageResource(R.mipmap.kuang);
                    isFirst = 0;
                }
                break;
        }
    }

    /**
     * 传参
     */
    private void getMaps() {
        String name = edShouhuoren.getText().toString();
        String phone = edPhone.getText().toString();
        String province = tvPrivoce.getText().toString();
        String city = tvCity.getText().toString();
        String district = tvDistrict.getText().toString();
        String jiedao = edJiedao.getText().toString();
        String address = edDetailAddress.getText().toString();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(province)
                || TextUtils.isEmpty(city) || TextUtils.isEmpty(district) || TextUtils.isEmpty(jiedao) || TextUtils.isEmpty(address)) {
            Toast.makeText(this, "数据不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (phone.length() != 11) {
            Toast.makeText(this, "电话号码格式不对", Toast.LENGTH_SHORT).show();
            return;
        }
        map.put("token", token);
        map.put("consigneeLat", latitude);//纬度
        map.put("consigneeLng", longitude);//经度
        map.put("consigneeName", name);//姓名
        map.put("consigneePhone", phone);//电话
        map.put("oneAddress", province);//省
        map.put("twoAddress", city);//市
        map.put("threeAddress", district);//区
        map.put("fourAddress", jiedao);//街道
        map.put("fiveAddress", address);//详细地址
        map.put("isFist", isFirst);
        if (consigneeId != null) {
            map.put("consigneeId", consigneeId);
        }
        addressPresenter.addAddress(map);
    }

    //初始化省份数据并设置适配器
    private void initProvince() {
        provinceList.clear();
        //初始化数据
        SQLiteDatabase database = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        Cursor cursor = database.rawQuery("select code,name from province", null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                byte[] blob = cursor.getBlob(1);
                String name = null;
                try {
                    name = new String(blob, "gbk");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                DbBean dbBean = new DbBean();
                dbBean.code = code;
                dbBean.name = name;
                provinceList.add(dbBean);
            }
        }

        database.close();
        cursor.close();

        //设置适配器
        mAdapter = new DbAdapter(this, provinceList);
        provinceListView.setAdapter(mAdapter);


    }

    //读取数据库到文件中
    private void initDbToFile() {

        dbFile = new File(getFilesDir(), "city.s3db");

        if (dbFile.exists()) {
            return;
        }

        Resources res = getResources();
        InputStream inputStream = res.openRawResource(R.raw.city);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(dbFile);
            byte[] byt = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(byt)) != -1) {
                fos.write(byt, 0, len);
            }
            inputStream.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //初始化PopupWindow
    private void initPopuoWindow() {
        View popupView = View.inflate(BianjiAddressActivity.this, R.layout.db_popupwindow1, null);
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        provinceListView = (ListView) popupView.findViewById(R.id.lv_province);
        cityListView = (ListView) popupView.findViewById(R.id.lv_city);
        districtListView = (ListView) popupView.findViewById(R.id.lv_district);
    }

    //省份的条目点击事件
    private void initProvinceListener() {

        provinceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                DbBean bean = (DbBean) provinceListView.getItemAtPosition(position);

                //根据类型TextView显示省
                String province = bean.name;
                tvPrivoce.setText(province);
                popupWindow.dismiss();

                //获取市的数据并设置适配器
                initCity(bean);

                //选完省后,市自动显示第一个内容
                DbBean cityBean = cityList.get(0);
                String city = cityBean.name;
                tvCity.setText(city);

                //自动显示完市后,再获取该市的所有区,并设置适配器
                initAutoDistrict(cityBean);

            }
        });
    }

    //获取市的数据并设置适配器
    private void initCity(DbBean bean) {

        //每获取新数据时,先清空之前数据
        cityList.clear();

        SQLiteDatabase database = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        String sql = "select code,name from city where  pcode = ?";
        String[] selectionArry = new String[]{bean.code};
        Cursor cursor = database.rawQuery(sql, selectionArry);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                byte[] blob = cursor.getBlob(1);
                String name = null;
                try {
                    name = new String(blob, "gbk");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                DbBean dbBean = new DbBean();
                dbBean.code = code;
                dbBean.name = name;
                cityList.add(dbBean);
            }
        }

        cursor.close();
        database.close();

        //设置适配器
        mAdapter = new DbAdapter(this, cityList);
        cityListView.setAdapter(mAdapter);

    }

    //自动显示完市后,再获取该市的所有区,并设置适配器
    private void initAutoDistrict(DbBean cityBean) {

        districtList.clear();

        SQLiteDatabase database = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        String sql = "select code,name from district where pcode = ?";
        String[] selectionArry = new String[]{cityBean.code};
        Cursor cursor = database.rawQuery(sql, selectionArry);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                String name = null;
                try {
                    name = new String(cursor.getBlob(1), "gbk");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                DbBean dbBean = new DbBean();
                dbBean.code = code;
                dbBean.name = name;
                districtList.add(dbBean);
            }
        }

        cursor.close();
        database.close();

        //设置适配器
        mAdapter = new DbAdapter(this, districtList);
        districtListView.setAdapter(mAdapter);
    }

    //市的条目点击事件
    private void initCityListener() {

        cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                DbBean bean = (DbBean) cityListView.getItemAtPosition(position);

                //根据类型TextView显示市
                String city = bean.name;
                tvCity.setText(city);
                popupWindow.dismiss();

                //获取区的数据并设置适配器
                initDistrict(bean);

                //选完市后,区自动显示第一个内容
                DbBean districtBean = districtList.get(1);
                String district = districtBean.name;
                tvDistrict.setText(district);
            }
        });
    }

    //获取区的数据并设置适配器
    private void initDistrict(DbBean bean) {

        districtList.clear();

        SQLiteDatabase database = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        String sql = "select code,name from district where pcode = ?";
        String[] selectionArry = new String[]{bean.code};
        Cursor cursor = database.rawQuery(sql, selectionArry);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                String name = null;
                try {
                    name = new String(cursor.getBlob(1), "gbk");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                DbBean dbBean = new DbBean();
                dbBean.code = code;
                dbBean.name = name;
                districtList.add(dbBean);
            }
        }

        cursor.close();
        database.close();

        //设置适配器
        mAdapter = new DbAdapter(this, districtList);
        districtListView.setAdapter(mAdapter);
    }

    //区的条目点击事件
    private void initDistrictListener() {

        districtListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                DbBean bean = (DbBean) districtListView.getItemAtPosition(position);

                //根据类型TextView显示市
                String city = bean.name;
                tvDistrict.setText(city);
                popupWindow.dismiss();

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 4) {
                Bundle bundle = data.getExtras();
                String province = bundle.getString("province");
                String city = bundle.getString("city");
                String destrict = bundle.getString("destrict");
                String street = bundle.getString("street");
                String address = bundle.getString("address");
                latitude = bundle.getDouble("latitude");
                longitude = bundle.getDouble("longitude");
                tvPrivoce.setText(province);
                tvCity.setText(city);
                tvDistrict.setText(destrict);
                edJiedao.setText(street);
                edDetailAddress.setText(address);
            }
        }
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "数据加载失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void editAddress(EditAddressBean editAddressBean) {
        if (editAddressBean.getState() == 0) {
            Toast.makeText(this, "访问失败", Toast.LENGTH_SHORT).show();
        } else if (editAddressBean.getState() == 1) {
            edShouhuoren.setText(editAddressBean.getData().getConsigneeName());
            edPhone.setText(editAddressBean.getData().getConsigneePhone());
            tvPrivoce.setText(editAddressBean.getData().getOneAddress());
            tvCity.setText(editAddressBean.getData().getTwoAddress());
            tvDistrict.setText(editAddressBean.getData().getThreeAddress());
            edJiedao.setText(editAddressBean.getData().getFourAddress());
            edDetailAddress.setText(editAddressBean.getData().getFiveAddress());
        }
    }

    @Override
    public void addAddress(AddAdressBean addAdressBean) {
        if (addAdressBean.getState() == 1) {
            if (addAdressBean.isData()) {
                finish();
            } else {
                Toast.makeText(this, "新增地址失败", Toast.LENGTH_SHORT).show();
            }
        } else if (addAdressBean.getState() == 0) {
            Toast.makeText(this, "访问失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (addressPresenter != null) {
            addressPresenter = null;
        }
        if (editAddressPresenter != null) {
            editAddressPresenter = null;
        }
    }

}
